package com.suning.sawp.service.impl.model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.suning.framework.dal.client.DalClient;
import com.suning.sawp.constants.CacheKeyConstants;
import com.suning.sawp.constants.ClerkConstants;
import com.suning.sawp.constants.LoggerConstants;
import com.suning.sawp.dto.mainpush.StoreManDto;
import com.suning.sawp.dto.storeman.Category;
import com.suning.sawp.intf.model.ModelConstant;
import com.suning.sawp.intf.model.ModelTaskAssignDetailsBean;
import com.suning.sawp.intf.model.ModelTaskMainBean;
import com.suning.sawp.intf.model.vo.ModelAssignDetailResponse;
import com.suning.sawp.intf.model.vo.ModelAssignTaskResponse;
import com.suning.sawp.intf.model.vo.ModelInventoryDetailResponse;
import com.suning.sawp.intf.model.vo.ModelInventoryTaskResponse;
import com.suning.sawp.intf.model.vo.ModelTaskBrandVo;
import com.suning.sawp.intf.model.vo.ModelTaskCateVo;
import com.suning.sawp.intf.model.vo.ModelTaskDetailVo;
import com.suning.sawp.intf.model.vo.ModelTaskInfoVo;
import com.suning.sawp.intf.storeman.StoreValidResult;
import com.suning.sawp.service.util.DateUtils;
import com.suning.sawp.service.util.RedisCacheUtils;
import com.suning.vgs.follow.remote.intf.StoreManRemoteService;
import com.suning.vgs.follow.remote.store.StoreManBaseDto;

/**
 * 新样机管理 <br>
 * 任务管理
 *
 * @author 15050519
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Service("modelTaskNewService")
public class ModelTaskNewServiceImpl {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoggerConstants.SAWP_SERVICE);

    /**
     * 任务状态已结束
     */
    private static final Integer TASK_OVER = Integer.valueOf("2");
    
    @Autowired
    ModelTaskDaoServiceImpl modelTaskDaoService;

    @Autowired
    ModelProbDaoServiceImpl modelProbDaoService;

    @Autowired
    StoreManRemoteService storeManRemoteService;

    @Resource
    RedisCacheUtils cacheUtils;
    
    @Resource
    DalClient dalClient;
    
    @Resource
    StaffInfoServiceImpl staffInfoServiceImpl;

    /**
     * 查询出未挂靠督导且未分配的品类编码列表
     */
    private List<String> queryNoCateCodes(String storeCode, Integer taskType, Long taskId) {
        List<String> result = new ArrayList<String>();
        // 查询出该门店下所有品类（除去已分配的）
        List<String> cateCodes = modelTaskDaoService.queryTaskCates(storeCode, taskType, taskId);
        if (CollectionUtils.isNotEmpty(cateCodes)) {
            Set<String> set = new HashSet<String>();
            set.addAll(cateCodes);
            // 查询rsf接口，筛选出未挂靠督导的品类
            List<StoreValidResult> validList  = staffInfoServiceImpl.validHasGuide(storeCode, cateCodes);
            //切换接口
            //List<StoreGuideValidResult> validList = storeManRemoteService.validHasGuide(storeCode, cateCodes);
            if (CollectionUtils.isNotEmpty(validList)) {
                for (StoreValidResult storeGuideValidResult : validList) {
                    if (!storeGuideValidResult.getGuideExist()) {
                        if (set.contains(storeGuideValidResult.getCateCode())) {
                            // 该品类为任务中且无挂靠督导的品类
                            result.add(storeGuideValidResult.getCateCode());
                        }
                    }
                }
            }
        }
        return result;
    }
    
    /**
     * 根据员工ID查询员工名称
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param staffId
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public String queryStaffName(String staffId) {
        // 工号不为空时
        if (StringUtils.isNotBlank(staffId)) {
            String cacheKey = String.format(CacheKeyConstants.MODEL_STAFF_NAME_BY_ID, staffId);
            // 首先从缓存中拉取数据，缓存不存在则执行下面的方法从数据库中拉取数据
            String name = getCacheValue(cacheKey);
            if (StringUtils.isNotBlank(name)) {
                return name;
            }
            StoreManBaseDto man = storeManRemoteService.queryStoreManBaseInfoByStaffId(staffId);
            if (null != man) {
                name = man.getStoreManName() + "(" + staffId + ")";
                // 加缓存
                setCacheAndExpire(cacheKey, name, CacheKeyConstants.ONE_WEEK_EXPIRE_TIME);
                return name;
            }
            return staffId;
        }
        return "--";
    }
    
    /**
     * 从缓存中取数据
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param cacheKey
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private String getCacheValue(String cacheKey) {
        try {
            return cacheUtils.get(cacheKey);
        } catch (Exception e) {
            LOGGER.error("getCacheValue error,key=" + cacheKey, e);
        }
        return null;
    }
    
    /**
     * 设置缓存时间
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param cacheKey
     * @param value
     * @param expireTime
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private void setCacheAndExpire(String cacheKey, String value, int expireTime) {
        try {
            cacheUtils.setex(cacheKey, expireTime, value);
        } catch (Exception e) {
            LOGGER.error("getCacheValue error,key=" + cacheKey, e);
        }
    }
    
    /**
     * 根据门店编码,品类编码查询督导名称
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param storeCode
     * @param cateCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public String queryStaffName(String storeCode, String cateCode) {
        // 先从缓存中取数据
        String cacheKey = String.format(CacheKeyConstants.MODEL_GUIDE_NAME_BY_CATE, storeCode, cateCode);
        String name = this.getCacheValue(cacheKey);
        if (StringUtils.isNotBlank(name)) {
            return name;
        }
        List<String> categoryCodes = new ArrayList<String>();
        categoryCodes.add(cateCode);
//        List<StoreGuideValidResult> guides = storeManRemoteService.validHasGuide(storeCode, categoryCodes);
        List<StoreValidResult> guides  = staffInfoServiceImpl.validHasGuide(storeCode, categoryCodes);
        // 数据不为空
        if (CollectionUtils.isNotEmpty(guides)) {
            // 默认一个品类,只取第一条
            StoreValidResult guide = guides.get(0);
            Set<String> names= new HashSet<String>();
            // 存在督导时
            if (null != guide && guide.getGuideExist() && CollectionUtils.isNotEmpty(guide.getStaffIds())) {
                for (String id : guide.getStaffIds()) {
                    names.add(queryStaffName(id));
                }
            } 
            // 有名字时，按照逗号分隔成字符串
            if (names.size() > 0) {
                name = org.springframework.util.StringUtils.arrayToDelimitedString(names.toArray(), ",");
                // 加入缓存
                setCacheAndExpire(cacheKey, name, CacheKeyConstants.HALF_HOUR_EXPIRE_TIME);
                return name;
            }
        }
        return "--";
    }

    /**
     * 查询店长，督导，促销员分配任务
     * 功能描述: <br>
     * 店长查询门店所有的任务列表<br>
     * 督导查询品类相关的任务,或临时分配的任务<br>
     * 促销员查询临时分配的任务<br>
     * 状态有待分配、分配中、待盘点、盘点中、已提交、已结束
     * @param storeMan
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public ModelAssignTaskResponse queryMyAssignTasks(StoreManDto storeMan, int index, int size){
        LOGGER.info("enter queryMyAssignTasks service,index={},size={}", index, size);
        ModelAssignTaskResponse resp = new ModelAssignTaskResponse();
        String positionId = storeMan.getPositionId();
        String staffId = storeMan.getStaffId();
        // 店长权限
        if (ClerkConstants.STORE_KEEPER.equals(positionId) || ClerkConstants.DEPUTY_STORE_KEEPER.equals(positionId)) {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("storeCode", storeMan.getStoreCode());
            paramMap.put("index", index);
            paramMap.put("size", size);
            List<ModelTaskAssignDetailsBean> list = dalClient.queryForList("MODEL_TASK_NEW.SELECT_ASSIGN_TASKS", paramMap,ModelTaskAssignDetailsBean.class);
            resp.setList(convertKeeperTasks(list, storeMan.getStoreCode(), staffId));
        } else if (ClerkConstants.SALE_GUIDE.equals(positionId)) {
            List<String> cates;
            if (CollectionUtils.isNotEmpty(storeMan.getCategories())) {
                // 督导权限
                cates = Lists.transform(storeMan.getCategories(), new Function<Category, String>(){
                    @Override
                    public String apply(Category input) {
                        return input.getCategoryCode();
                    }
                });
            } else {
                cates = new ArrayList<String>();
                // 默认空品类
                cates.add("");
            }
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("storeCode", storeMan.getStoreCode());
            paramMap.put("assignStaff2", staffId);
            paramMap.put("cates", cates);
            paramMap.put("index", index);
            paramMap.put("size", size);
            List<ModelTaskAssignDetailsBean> list = dalClient.queryForList("MODEL_TASK_NEW.SELECT_ASSIGN_TASKS", paramMap,ModelTaskAssignDetailsBean.class);
            resp.setList(convertGuideTasks(list, storeMan.getStoreCode(), staffId, cates));
        } else {
            // 促销员 营业员权限
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("storeCode", storeMan.getStoreCode());
            paramMap.put("assignStaff", staffId);
            paramMap.put("index", index);
            paramMap.put("size", size);
            List<ModelTaskAssignDetailsBean> list = dalClient.queryForList("MODEL_TASK_NEW.SELECT_ASSIGN_TASKS", paramMap,ModelTaskAssignDetailsBean.class);
            resp.setList(convertGuideTasks(list, storeMan.getStoreCode(), staffId, null));
        }
        LOGGER.info("exit queryMyAssignTasks service,index={},size={}", index, size);
        return resp;
    }
    
    /**
     * 处理督导分配任务和展示数据
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param list
     * @param storeCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private List<ModelTaskInfoVo> convertGuideTasks(List<ModelTaskAssignDetailsBean> list, String storeCode, String staffId, List<String> cates) {
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        ModelTaskInfoVo taskVo;
        List<ModelTaskInfoVo> taskList = new ArrayList<ModelTaskInfoVo>();
        // 清单数据
        List<ModelTaskAssignDetailsBean> tasks;
        for (ModelTaskAssignDetailsBean detail : list) {
            // 查询任务清单
            tasks = queryGuideTasks(detail, storeCode, cates, staffId);
            // 如果任务为空,则不处理数据
            if (CollectionUtils.isEmpty(tasks)) {
                LOGGER.warn("convertGuideTasks QUERY_GUIDE_TASKS is null, storeCode={},taskId={}", storeCode, detail.getTaskId());
                continue;
            }
            taskVo = new ModelTaskInfoVo();
            taskVo.setTaskId(detail.getTaskId().toString());
            taskVo.setStartTime(DateUtils.getDateStrByFormat(detail.getStartTime(), "yyyy.MM.dd"));
            taskVo.setEndTime(DateUtils.getDateStrByFormat(detail.getEndTime(), "yyyy.MM.dd"));
            taskVo.setStorageCode(detail.getStorageCode());
            // 设置品类
            List<ModelTaskCateVo> taskCates = convertCate(tasks);
            taskVo.setCates(taskCates);
            // 设置盘点数
            taskVo.setInventoryCnt(getInventoryNum(detail.getTaskId(), storeCode, taskCates));
            // 根据门店,品类查询样机清单数量
            taskVo.setModelTotal(getModelMainListCnt(storeCode, taskCates));
            // 设置任务状态
            if (TASK_OVER.equals(detail.getRunStatus())) {
                taskVo.setTaskStatusCode(ModelConstant.TASK_STATUS_CODE_JS);
            } else {
                // 根据品类品牌状态,区分出任务状态
                taskVo.setTaskStatusCode(getTaskStatusCode(tasks));
                // 设置任务操作类型
                if (ModelConstant.TASK_STATUS_CODE_YF.equals(taskVo.getTaskStatusCode()) 
                        || ModelConstant.TASK_STATUS_CODE_MF.equals(taskVo.getTaskStatusCode())) {
                    // 品牌分配 -02
                    taskVo.setOprType("02");
                }
            }
            taskList.add(taskVo);
        }
        return taskList;
    }
    
    /**
     * 根据任务是否是指定督导类型，查询任务清单列表
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param detail
     * @param storeCode
     * @param cates
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private List<ModelTaskAssignDetailsBean> queryGuideTasks(ModelTaskAssignDetailsBean detail, String storeCode, 
            List<String> cates, String staffId) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("storeCode", storeCode);
        paramMap.put("taskId", detail.getTaskId());
        // 促销员或者是指定督导的
        if (CollectionUtils.isEmpty(cates)) {
            // 存在则根据工号查询关联品类,再把清单查询出来
            paramMap.put("staffId", staffId);
            // 查询出任务清单数据
            return dalClient.queryForList("MODEL_TASK_NEW.QUERY_NO_GUIDE_TASKS", paramMap,ModelTaskAssignDetailsBean.class);
        } else {
            paramMap.put("staffId", staffId);
            // 不是则根据自身品类查询关联任务清单
            paramMap.put("cateStr", cates);
            // 查询出任务清单数据
            return dalClient.queryForList("MODEL_TASK_NEW.QUERY_GUIDE_TASKS", paramMap,ModelTaskAssignDetailsBean.class);
        }
    }
    
    /**
     * 处理店长分配任务和展示数据
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param list
     * @param storeCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private List<ModelTaskInfoVo> convertKeeperTasks(List<ModelTaskAssignDetailsBean> list, String storeCode, String staffId) {
        // 判断是否任务为空
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        // 将任务ID组装成集合
        List<Long> ids = Lists.transform(list, new Function<ModelTaskAssignDetailsBean, Long>(){
            @Override
            public Long apply(ModelTaskAssignDetailsBean input) {
                return input.getTaskId();
            }
        });
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("storeCode", storeCode);
        paramMap.put("taskIds", ids);
        // 查询出任务清单数据
        List<ModelTaskAssignDetailsBean> tasks = dalClient.queryForList("MODEL_TASK_NEW.SELECT_KEEPER_ASSIGN_TASKS", paramMap,ModelTaskAssignDetailsBean.class);
        if (CollectionUtils.isEmpty(tasks)) {
            LOGGER.warn("SELECT_KEEPER_ASSIGN_TASKS is null,storeCode={},ids={}", storeCode, ids);
            return Collections.emptyList();
        }
        Map<Long, List<ModelTaskAssignDetailsBean>> map = getTaskMap(tasks);
        ModelTaskInfoVo taskVo;
        List<ModelTaskInfoVo> taskList = new ArrayList<ModelTaskInfoVo>();
        for (ModelTaskAssignDetailsBean detail : list) {
            taskVo = new ModelTaskInfoVo();
            taskVo.setTaskId(detail.getTaskId().toString());
            taskVo.setStartTime(DateUtils.getDateStrByFormat(detail.getStartTime(), "yyyy.MM.dd"));
            taskVo.setEndTime(DateUtils.getDateStrByFormat(detail.getEndTime(), "yyyy.MM.dd"));
            taskVo.setStorageCode(detail.getStorageCode());
            // 设置品类
            if(CollectionUtils.isEmpty(map.get(detail.getTaskId()))){
                continue;
            }
            List<ModelTaskCateVo> cates = convertCate(map.get(detail.getTaskId()));
            taskVo.setCates(cates);
            // 设置盘点数
            taskVo.setInventoryCnt(getInventoryNum(detail.getTaskId(), storeCode, cates));
            // 设置总数
            taskVo.setModelTotal(getModelMainListCnt(storeCode, cates));
            
            // 任务已结束
            if (TASK_OVER.equals(detail.getRunStatus())) {
                taskVo.setTaskStatusCode(ModelConstant.TASK_STATUS_CODE_JS);
            } else {
                // 根据品类品牌状态,区分出任务状态
                taskVo.setTaskStatusCode(getTaskStatusCode(map.get(detail.getTaskId())));
                // 查询没有督导且还没被分配品类 , 
                // 去除簇商品任务，所有任务都是盘点任务 12061818
                List<String> noGuideCate = queryNoCateCodes(storeCode, null, detail.getTaskId());
                if (CollectionUtils.isNotEmpty(noGuideCate)) {
                    taskVo.setNeedAssign(noGuideCate.size());
                    // 品类分配
                    taskVo.setOprType("01");
                } else {
                    // 是指定督导的
                    // 则查询库,确定任务的品类盘点是否已经分配完成
                    List<String> noAssignBrands = getNoAssignTaskCnt(detail.getTaskId(), storeCode, staffId, null);
                    // 品牌分配-02
                    taskVo.setOprType(CollectionUtils.isNotEmpty(noAssignBrands) ? "02" : null);
                }
            }
            taskList.add(taskVo);
        }
        return taskList;
    }
    
    /**
     * 查询指定督导的品类任务是否已分配完成
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param taskId
     * @param storeCode
     * @param staffId
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private List<String> getNoAssignTaskCnt(Long taskId, String storeCode, String staffId, String cateCode) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("storeCode", storeCode);
        paramMap.put("taskId", taskId);
        paramMap.put("staffId", staffId);
        if (StringUtils.isNotBlank(cateCode)) {
            paramMap.put("cateCode", cateCode);
        }
        return dalClient.queryForList("MODEL_TASK_NEW.GET_NO_ASSIGN_TASK_BRANDS", paramMap, String.class);
    }
    
    /**
     * 查询指定任务人
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param taskId
     * @param storeCode
     * @param cateCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private String getTaskAssignPerson(Long taskId, String storeCode, String cateCode) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("storeCode", storeCode);
        paramMap.put("taskId", taskId);
        paramMap.put("cateCode", cateCode);
        return dalClient.queryForObject("MODEL_TASK_NEW.GET_TASK_ASSIGN_PERSON", paramMap, String.class);
    }
    
    /**
     * 核算任务状态
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param list
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private String getTaskStatusCode(List<ModelTaskAssignDetailsBean> list) {
        Set<String> status = new HashSet<String>();
        String str = null;
        for (ModelTaskAssignDetailsBean bean : list) {
            // 未分配
            if (ModelConstant.TASK_ASSIGN_STATUS_NO.equals(bean.getAssignStatus())) {
                status.add("a01");
                // 已分配
            } else if (ModelConstant.TASK_ASSIGN_STATUS_DONE.equals(bean.getAssignStatus())) {
                status.add("a02");
            }
            // 未提交
            if (ModelConstant.CHECK_TASK_STATUS_NO.equals(bean.getCheckTaskStatus())) {
                status.add("a03");
                // 已提交
            } else if (ModelConstant.CHECK_TASK_STATUS_DONE.equals(bean.getCheckTaskStatus())) {
                status.add("a04");
            } else if (ModelConstant.CHECK_TASK_STATUS_OVER.equals(bean.getCheckTaskStatus())) {
                // 比较完成预示任务结束
                status.add("a05");
            }
        }
        // 存在未分配任务
        if (status.contains("a01")) {
            // 也存在已分配任务
            if (status.contains("a02")) {
                str = ModelConstant.TASK_STATUS_CODE_YF;
            } else {
                str = ModelConstant.TASK_STATUS_CODE_MF;
            }
        } else if (status.contains("a03")) {
            // 存在为提交, 同时也存在已提交
            if (status.contains("a04")) {
                str = ModelConstant.TASK_STATUS_CODE_YP;
            } else {
                str = ModelConstant.TASK_STATUS_CODE_MP;
            }
        } else if (status.contains("a04")) {
            // 存在已分配,已提交,则为已提交
            str = ModelConstant.TASK_STATUS_CODE_YT;
        } else {
            // 默认已结束
            str = ModelConstant.TASK_STATUS_CODE_JS;
        }
        return str;
    }
    
    /**
     * 判断某个品牌的状态
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param task
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private String getTaskStatusCode(ModelTaskAssignDetailsBean task) {
        String str = null;
        // 未提交,即为待盘点
        if (ModelConstant.CHECK_TASK_STATUS_NO.equals(task.getCheckTaskStatus())) {
            str = ModelConstant.TASK_STATUS_CODE_MP;
            // 已提交
        } else if (ModelConstant.CHECK_TASK_STATUS_DONE.equals(task.getCheckTaskStatus())) {
            str = ModelConstant.TASK_STATUS_CODE_YT;
        } else if (ModelConstant.CHECK_TASK_STATUS_OVER.equals(task.getCheckTaskStatus())) {
            // 比较完成预示任务结束
            str = ModelConstant.TASK_STATUS_CODE_JS;
        }
        return str;
    }
    
    /**
     * 同一个品类,下挂所有品牌数据
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param list
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private List<ModelTaskCateVo> convertCate(List<ModelTaskAssignDetailsBean> list) {
        Map<String, ModelTaskCateVo> cates = new HashMap<String, ModelTaskCateVo>();
        ModelTaskCateVo cate;
        ModelTaskBrandVo brand;
        for (ModelTaskAssignDetailsBean bean : list) {
            cate = cates.get(bean.getCateCode());
            if (null == cate) {
                cate = new ModelTaskCateVo();
                cate.setCateName(bean.getCateName());
                cate.setCateCode(bean.getCateCode());
            }
            brand = new ModelTaskBrandVo();
            brand.setBrandCode(bean.getBranch9code());
            brand.setBrandName(bean.getBranchName());
            if (CollectionUtils.isEmpty(cate.getBrands())) {
                cate.setBrands(new ArrayList<ModelTaskBrandVo>());
            }
            cate.getBrands().add(brand);
            cates.put(bean.getCateCode(), cate);
        }
        return new ArrayList<ModelTaskCateVo>(cates.values());
    }
    
    /**
     * 查询多品类样机盘点数量
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param taskId
     * @param cates
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private int getInventoryNum(Long taskId, String storeCode, List<ModelTaskCateVo> cates) {
        int totalNum = 0;
        List<String> brands;
        for (ModelTaskCateVo cate : cates) {
            // 列出品牌集合
            brands = Lists.transform(cate.getBrands(), new Function<ModelTaskBrandVo, String>(){
                @Override
                public String apply(ModelTaskBrandVo input) {
                    return input.getBrandCode();
                }
            });
            totalNum += getInventoryNum(taskId, storeCode, cate.getCateCode(), brands);
        }
        return totalNum;
    }
    
    /**
     * 查询单品类样机盘点数量
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param taskId
     * @param cateCode
     * @param brands
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private int getInventoryNum(Long taskId, String storeCode, String cateCode, List<String> brands) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("taskId", taskId);
        paramMap.put("storeCode", storeCode);
        if (StringUtils.isNotBlank(cateCode)) {
            paramMap.put("cateCode", cateCode);
        }
        if (CollectionUtils.isNotEmpty(brands)) {
            paramMap.put("brands", brands);
        }
        Integer checks = dalClient.queryForObject("MODEL_TASK_NEW.GET_CHECK_CNT", paramMap, Integer.class);
        if (null != checks) {
            return checks.intValue();
        }
        return 0;
    }
    
    /**
     * 查询多个品类下样机清单总数
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param storeCode
     * @param cates
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private int getModelMainListCnt(String storeCode, List<ModelTaskCateVo> cates) {
        int totalNum = 0;
        List<String> brands;
        for (ModelTaskCateVo cate : cates) {
            // 列出品牌集合
            brands = Lists.transform(cate.getBrands(), new Function<ModelTaskBrandVo, String>(){
                @Override
                public String apply(ModelTaskBrandVo input) {
                    return input.getBrandCode();
                }
            });
            totalNum += getModelMainListCnt(storeCode, cate.getCateCode(), brands);
        }
        return totalNum;
    }
    
    /**
     * 查询单品类下样机清单数量
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param storeCode
     * @param cateCode
     * @param brands
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private int getModelMainListCnt(String storeCode, String cateCode, List<String> brands) {
        // 从缓存中取缓存数据
        String cacheKey = String.format(CacheKeyConstants.MODEL_CATE_BRAND_TOTAL, storeCode, cateCode,
                org.springframework.util.StringUtils.arrayToCommaDelimitedString(brands.toArray()));
        String name = this.getCacheValue(cacheKey);
        if (StringUtils.isNotBlank(name)) {
            try {
                return Integer.parseInt(name);
            } catch (Exception e) {
                LOGGER.warn("getModelMainListCnt cache error", e);
            }
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("storeCode", storeCode);
        paramMap.put("cateCode", cateCode);
        paramMap.put("brands", brands);
        Integer modelCnt = dalClient.queryForObject("MODEL_TASK_NEW.GET_MODEL_MAIN_LIST_CNT", paramMap, Integer.class);
        if (null != modelCnt) {
            // 缓存一天时间
            this.setCacheAndExpire(cacheKey, modelCnt.toString(), CacheKeyConstants.ONE_DAY_EXPIRE_TIME);
            return modelCnt.intValue();
        }
        return 0;
    }
    
    /**
     * 将任务按照任务ID转换成Map对象,方便获取
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param tasks
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private Map<Long, List<ModelTaskAssignDetailsBean>> getTaskMap(List<ModelTaskAssignDetailsBean> tasks) {
        Map<Long, List<ModelTaskAssignDetailsBean>> map = new HashMap<Long, List<ModelTaskAssignDetailsBean>>();
        List<ModelTaskAssignDetailsBean> list;
        if (CollectionUtils.isNotEmpty(tasks)) { 
            for (ModelTaskAssignDetailsBean task : tasks) {
                list = map.get(task.getTaskId());
                if (CollectionUtils.isEmpty(list)) {
                    list = new ArrayList<ModelTaskAssignDetailsBean>();
                }
                list.add(task);
                map.put(task.getTaskId(), list);
            }
        }
        return map;
    }
    
    /**
     * 根据品类把任务存在MAP中
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param tasks
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private Map<String, List<ModelTaskAssignDetailsBean>> getTaskMapByCate(List<ModelTaskAssignDetailsBean> tasks) {
        Map<String, List<ModelTaskAssignDetailsBean>> map = new HashMap<String, List<ModelTaskAssignDetailsBean>>();
        List<ModelTaskAssignDetailsBean> list;
        if (CollectionUtils.isNotEmpty(tasks)) { 
            for (ModelTaskAssignDetailsBean task : tasks) {
                list = map.get(task.getCateCode());
                if (CollectionUtils.isEmpty(list)) {
                    list = new ArrayList<ModelTaskAssignDetailsBean>();
                }
                list.add(task);
                map.put(task.getCateCode(), list);
            }
        }
        return map;
    }
    
    /**
     * 查询店长，督导，促销员盘点任务
     * 功能描述: <br>
     * 店长查询临时分给自己的盘点任务<br>
     * 督导查询临时分给自己的盘点任务<br>
     * 促销员查询分给自己的任务，或临时分给自己的盘点任务<br>
     * 状态有待盘点、盘点中、已提交、已结束
     *
     * @param storeMan
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public ModelInventoryTaskResponse queryMyInventoryTasks(StoreManDto storeMan, int index, int size){
        LOGGER.info("enter queryMyInventoryTasks service,index={},size={}", index, size);
        ModelInventoryTaskResponse resp = new ModelInventoryTaskResponse();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        List<ModelTaskInfoVo> taskList = new ArrayList<ModelTaskInfoVo>();
        paramMap.put("storeCode", storeMan.getStoreCode());
        paramMap.put("staffId", storeMan.getStaffId());
        paramMap.put("index", index);
        paramMap.put("size", size);
        // 查询出任务清单数据
        List<ModelTaskMainBean> taskPage = dalClient.queryForList("MODEL_TASK_NEW.QUERY_INVENTORY_TASKS_PAGE", paramMap, ModelTaskMainBean.class);
        // 判断是否存在盘点任务
        if (CollectionUtils.isEmpty(taskPage)) {
            // 设置返回对象
            resp.setList(taskList);
            LOGGER.warn("exit queryMyInventoryTasks service,taskPage is null,staffId={}", storeMan.getStaffId());
            return resp;
        }
        // 将任务Id封装成集合
        List<Long> taskIds = Lists.transform(taskPage, new Function<ModelTaskMainBean, Long>(){
            @Override
            public Long apply(ModelTaskMainBean input) {
                return input.getTaskId();
            }});
        paramMap.put("taskIds", taskIds);
        // 查询出任务清单数据
        List<ModelTaskAssignDetailsBean> tasks = dalClient.queryForList("MODEL_TASK_NEW.QUERY_INVENTORY_TASKS", paramMap,ModelTaskAssignDetailsBean.class);
        // 将清单数据按照任务ID封装进Map中
        Map<Long, List<ModelTaskAssignDetailsBean>> map = getTaskMap(tasks);
        // 循环封装数据
        ModelTaskInfoVo taskVo;
        for (ModelTaskMainBean detail : taskPage) {
            taskVo = new ModelTaskInfoVo();
            taskVo.setTaskId(detail.getTaskId().toString());
            taskVo.setStartTime(DateUtils.getDateStrByFormat(detail.getStartTime(), "yyyy.MM.dd"));
            taskVo.setEndTime(DateUtils.getDateStrByFormat(detail.getEndTime(), "yyyy.MM.dd"));
            taskVo.setStorageCode(detail.getStorageCode());
            // 设置品类
            List<ModelTaskCateVo> cates = convertCate(map.get(detail.getTaskId()));
            taskVo.setCates(cates);
            // 设置盘点数
            taskVo.setInventoryCnt(getInventoryNum(detail.getTaskId(), storeMan.getStoreCode(), cates));
            // 根据门店,品类查询样机清单数量
            taskVo.setModelTotal(getModelMainListCnt(storeMan.getStoreCode(), cates));
            // 设置任务状态
            if (TASK_OVER.equals(detail.getRunStatus())) {
                taskVo.setTaskStatusCode(ModelConstant.TASK_STATUS_CODE_JS);
            } else {
                // 根据品类品牌状态,区分出任务状态
                taskVo.setTaskStatusCode(getTaskStatusCode(map.get(detail.getTaskId())));
                // 设置任务操作类型
                if (ModelConstant.TASK_STATUS_CODE_YP.equals(taskVo.getTaskStatusCode()) 
                        || ModelConstant.TASK_STATUS_CODE_MP.equals(taskVo.getTaskStatusCode())) {
                    // 品牌盘点-03
                    taskVo.setOprType("03");
                }
            }
            taskList.add(taskVo);
        }
        // 设置返回对象
        resp.setList(taskList);
        LOGGER.info("exit queryMyInventoryTasks service,index={},size={}", index, size);
        return resp;
    }
    
    /**
     * 查询店长，督导，促销员分配任务详情
     * 功能描述: <br>
     * 店长查询任务下品类级详情，分配人，状态<br>
     * 督导查询品类级详情，盘点人，状态<br>
     * 促销员品类级详情，盘点人，状态<br>
     *
     * @param storeMan
     * @param taskId
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public ModelAssignDetailResponse queryMyAssignTaskDetail(StoreManDto storeMan, Long taskId){
        LOGGER.info("enter queryMyAssignTaskDetail service,taskId={}", taskId);
        String positionId = storeMan.getPositionId();
        // 店长权限
        if (ClerkConstants.STORE_KEEPER.equals(positionId) || ClerkConstants.DEPUTY_STORE_KEEPER.equals(positionId)) {
            return getKeeperTaskDetail(storeMan.getStoreCode(), taskId, storeMan.getStaffId());
        } else if (ClerkConstants.SALE_GUIDE.equals(positionId)) {
            // 督导权限
            List<String> cates;
            if (CollectionUtils.isNotEmpty(storeMan.getCategories())) {
                // 督导权限
                cates = Lists.transform(storeMan.getCategories(), new Function<Category, String>(){
                    @Override
                    public String apply(Category input) {
                        return input.getCategoryCode();
                    }
                });
            } else {
                cates = new ArrayList<String>();
                // 默认空品类
                cates.add("");
            }
            return getGuideTaskDetail(storeMan.getStoreCode(), taskId, storeMan.getStaffId(), cates);
        } else {
            // 促销员 营业员权限
            return getGuideTaskDetail(storeMan.getStoreCode(), taskId, storeMan.getStaffId(), null);
        }
    }
    
    /**
     * 查询督导，促销员分配任务详情
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param storeMan
     * @param taskId
     * @param staffId
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private ModelAssignDetailResponse getGuideTaskDetail(String storeCode, Long taskId, String staffId, List<String> guideCates) {
        ModelAssignDetailResponse resp = new ModelAssignDetailResponse();
        List<ModelTaskDetailVo> details = new ArrayList<ModelTaskDetailVo>(); 
        // 根据任务ID, 门店编码查询出任务详情信息
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("storeCode", storeCode);
        paramMap.put("taskId", taskId);
        // 促销员
        if (CollectionUtils.isEmpty(guideCates)) {
            paramMap.put("staffId", staffId);
        }
        // 查询任务详情
        ModelTaskAssignDetailsBean taskMain = dalClient.queryForObject("MODEL_TASK_NEW.GET_ASSIGN_TASK_DETAIL", paramMap, ModelTaskAssignDetailsBean.class);
        List<ModelTaskAssignDetailsBean> tasks = null;
        if (null == taskMain || null == taskMain.getTaskId()) {
            LOGGER.warn("getGuideTaskDetail is null,taskId={},staffId={}", taskId, staffId);
            resp.setDetails(details);
            return resp;
        }
        // 查询清单列表
        tasks = this.queryGuideTasks(taskMain, storeCode, guideCates, staffId);
        // 返回空
        if (CollectionUtils.isEmpty(tasks)) {
            LOGGER.warn("getGuideTaskDetail detail is null,taskId={},taskMain={}", taskId, taskMain);
            resp.setDetails(details);
            return resp;
        }
        // 拼接对象
        resp.setTaskId(String.valueOf(taskId));
        resp.setStartTime(DateUtils.getDateStrByFormat(taskMain.getStartTime(), "yyyy.MM.dd"));
        resp.setEndTime(DateUtils.getDateStrByFormat(taskMain.getEndTime(), "yyyy.MM.dd"));
        resp.setStorageCode(taskMain.getStorageCode());
        // 按照品类分组
        Map<String, List<ModelTaskAssignDetailsBean>> cateMap = getTaskMapByCate(tasks);
        List<ModelTaskAssignDetailsBean> cateTask;
        // 设置品类
        List<ModelTaskCateVo> cates = convertCate(tasks);
        Set<String> status = new HashSet<String>();
        for (ModelTaskCateVo cate : cates) {
            // 取出该品类下品牌集合
            cateTask = cateMap.get(cate.getCateCode());
            details.addAll(convertAssignData(taskMain, storeCode, cate.getCateCode(), cateTask));
            String statusCode = getTaskStatusCode(cateTask);
            if (!TASK_OVER.equals(taskMain.getRunStatus()) && ( ModelConstant.TASK_STATUS_CODE_MF.equals(statusCode) 
                    || ModelConstant.TASK_STATUS_CODE_YF.equals(statusCode))) {
                // 品类的品牌分配-02
                status.add("02");
            }
        }
        // 设置任务操作类型，品类操作优先品牌操作
        if (status.contains("02")) {
            resp.setOprType("02");
        }
        resp.setDetails(details);
        return resp;
    }
    
    /**
     * 店长查询分配任务详情
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param storeCode
     * @param taskId
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private ModelAssignDetailResponse getKeeperTaskDetail(String storeCode, Long taskId, String staffId) {
        ModelAssignDetailResponse resp = new ModelAssignDetailResponse();
        List<ModelTaskDetailVo> details = new ArrayList<ModelTaskDetailVo>(); 
        ModelTaskDetailVo detail;
        // 根据任务ID, 门店编码查询出任务详情信息
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("storeCode", storeCode);
        paramMap.put("taskId", taskId);
        ModelTaskAssignDetailsBean taskMain = dalClient.queryForObject("MODEL_TASK_NEW.GET_ASSIGN_TASK_DETAIL", paramMap, ModelTaskAssignDetailsBean.class);
        // 查询出任务清单数据
        List<ModelTaskAssignDetailsBean> tasks = dalClient.queryForList("MODEL_TASK_NEW.QUERY_KEEPER_ASSIGN_TASK_DETAIL", paramMap,ModelTaskAssignDetailsBean.class);
        if (null == taskMain || null == taskMain.getTaskId() || CollectionUtils.isEmpty(tasks)) {
            LOGGER.warn("getKeeperTaskDetail detail is null,taskId={},taskMain={}", taskId, taskMain);
            resp.setDetails(details);
            return resp;
        }
        resp.setTaskId(String.valueOf(taskId));
        resp.setStartTime(DateUtils.getDateStrByFormat(taskMain.getStartTime(), "yyyy.MM.dd"));
        resp.setEndTime(DateUtils.getDateStrByFormat(taskMain.getEndTime(), "yyyy.MM.dd"));
        resp.setStorageCode(taskMain.getStorageCode());
        // 查询没有督导且还没被分配品类
        // 所有任务均为盘点任务，去除簇商品任务
        List<String> noGuideCate = queryNoCateCodes(storeCode, null, taskMain.getTaskId());
        Set<String> noGuideCateSet = new HashSet<String>();
        if (CollectionUtils.isNotEmpty(noGuideCate)) {
            for (String cate : noGuideCate) {
                noGuideCateSet.add(cate);
            }
        }
        // 按照品类分组
        Map<String, List<ModelTaskAssignDetailsBean>> cateMap = getTaskMapByCate(tasks);
        List<ModelTaskAssignDetailsBean> cateTask;
        // 设置品类
        List<ModelTaskCateVo> cates = convertCate(tasks);
        Set<String> status = new HashSet<String>();
        List<String> brands;
        for (ModelTaskCateVo cate : cates) {
            detail = new ModelTaskDetailVo();
            detail.setCate(cate);
            cateTask = cateMap.get(cate.getCateCode());
            // 查询该品类是否存在督导
            if (noGuideCateSet.contains(cate.getCateCode())) {
                // 没有督导则返回空
                detail.setAssignPerson("--");
                // 品类分配-01
                status.add("01");
            } else {
                // 没有督导但已分配, 再判断督导是否是本人
                String assginPerson = getTaskAssignPerson(taskId, storeCode, cate.getCateCode());
                if (StringUtils.isNotBlank(assginPerson)) {
                    if (assginPerson.equals(staffId)) {
                        // 则查询库,确定任务的品类盘点是否已经分配完成
                        List<String> noAssignBrand = getNoAssignTaskCnt(taskId, storeCode, staffId, cate.getCateCode());
                        if (CollectionUtils.isNotEmpty(noAssignBrand)) {
                            // 品牌分配-02
                            status.add("02");
                        }
                        // 指定分配任务，重新组装
                        details.addAll(convertAssignData(taskMain, storeCode, cate.getCateCode(), cateTask));
                        // 组装下一个品类数据
                        continue;
                    } else {
                        detail.setAssignPerson(queryStaffName(assginPerson));
                    }
                } else {
                    // 根据门店编码+品类查询督导信息
                    detail.setAssignPerson(queryStaffName(storeCode, cate.getCateCode()));
                }
            }
            // 样机品类下品牌集合
            brands = Lists.transform(cate.getBrands(), new Function<ModelTaskBrandVo, String>(){
                @Override
                public String apply(ModelTaskBrandVo input) {
                    return input.getBrandCode();
                }
            });
            // 设置盘点数
            detail.setInventoryCnt(getInventoryNum(taskMain.getTaskId(), storeCode, cate.getCateCode(), brands));
            // 根据门店,品类查询样机清单数量
            detail.setModelTotal(getModelMainListCnt(storeCode, cate.getCateCode(), brands));
            // 设置任务状态
            if (TASK_OVER.equals(taskMain.getRunStatus())) {
                detail.setTaskStatusCode(ModelConstant.TASK_STATUS_CODE_JS);
            } else {
                // 根据品类品牌状态,区分出品类状态
                detail.setTaskStatusCode(getTaskStatusCode(cateTask));
            }
            details.add(detail);
        }
        // 任务未结束时,可操作
        if (!TASK_OVER.equals(taskMain.getRunStatus())) {
            // 设置任务操作类型，品类操作优先品牌操作
            if (status.contains("01")) {
                // 品类分配-03
                resp.setOprType("01");
            } else if (status.contains("02")) {
                resp.setOprType("02");
            }
        }
        resp.setDetails(details);
        return resp;
    }
    
    /**
     * 
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param tasks
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private List<ModelTaskDetailVo> convertAssignData(ModelTaskAssignDetailsBean taskMain, String storeCode, String cateCode, List<ModelTaskAssignDetailsBean> tasks) {
        List<ModelTaskDetailVo> details = new ArrayList<ModelTaskDetailVo>(); 
        // 按照盘点人分组
        Map<String, List<ModelTaskAssignDetailsBean>> map = new HashMap<String, List<ModelTaskAssignDetailsBean>>();
        List<ModelTaskAssignDetailsBean> temp;
        for (ModelTaskAssignDetailsBean bean : tasks) {
            if (StringUtils.isBlank(bean.getAcceptStaff())) {
                bean.setAcceptStaff("--");
            }
            temp = map.get(bean.getAcceptStaff());
            if (null == temp) {
                temp = new ArrayList<ModelTaskAssignDetailsBean>();
            }
            temp.add(bean);
            map.put(bean.getAcceptStaff(), temp);
        }
        // 迭代器盘点人
        Iterator<String> it = map.keySet().iterator();
        // 迭代盘点人
        while(it.hasNext()) {
            String acceptStaff = it.next();
            ModelTaskDetailVo detail = new ModelTaskDetailVo();
            temp = map.get(acceptStaff);
            List<String> brands = Lists.transform(temp, new Function<ModelTaskAssignDetailsBean, String>(){
                @Override
                public String apply(ModelTaskAssignDetailsBean input) {
                    return input.getBranch9code();
                }
            });
            // 设置盘点数
            detail.setInventoryCnt(getInventoryNum(taskMain.getTaskId(), storeCode, cateCode, brands));
            // 根据门店,品类查询样机清单数量
            detail.setModelTotal(getModelMainListCnt(storeCode, cateCode, brands));
            // 一个品类,取第一条
            detail.setCate(convertCate(temp).get(0));
            // 设置任务状态
            if (TASK_OVER.equals(taskMain.getRunStatus())) {
                detail.setTaskStatusCode(ModelConstant.TASK_STATUS_CODE_JS);
            } else {
                // 根据品类品牌状态,区分出品类状态
                detail.setTaskStatusCode(getTaskStatusCode(temp));
            }
            // 没有盘点人的,默认设置了--
            if("--".equals(acceptStaff)) {
                detail.setInventoryPerson("--");
            } else {
                detail.setInventoryPerson(queryStaffName(acceptStaff));
            }
            details.add(detail);
        }
        return details;
    }
    
    
    
    /**
     * 查询店长，督导，促销员盘点任务详情
     * 功能描述: <br>
     * 查询任务的品牌级详情,分配人，状态
     *
     * @param storeMan
     * @param taskId
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public ModelInventoryDetailResponse queryMyInventoryTaskDetail(StoreManDto storeMan, Long taskId){
        LOGGER.info("enter queryMyInventoryTaskDetail service,taskId={}", taskId);
        ModelInventoryDetailResponse resp = new ModelInventoryDetailResponse();
        List<ModelTaskDetailVo> details = new ArrayList<ModelTaskDetailVo>();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("storeCode", storeMan.getStoreCode());
        paramMap.put("staffId", storeMan.getStaffId());
        paramMap.put("taskId", taskId);
        // 查询任务详情
        ModelTaskAssignDetailsBean taskMain = dalClient.queryForObject("MODEL_TASK_NEW.GET_INVENTORY_TASK_DETAIL", paramMap, ModelTaskAssignDetailsBean.class);
        // 查询出任务清单数据
        List<ModelTaskAssignDetailsBean> tasks = dalClient.queryForList("MODEL_TASK_NEW.QUERY_INVENTORY_TASK_DETAIL", paramMap,ModelTaskAssignDetailsBean.class);
        if (null == taskMain || null == taskMain.getTaskId() || CollectionUtils.isEmpty(tasks)) {
            LOGGER.warn("queryMyInventoryTaskDetail detail is null,taskId={},taskMain={}", taskId, taskMain);
            resp.setDetails(details);
            return resp;
        }
        resp.setTaskId(String.valueOf(taskId));
        resp.setStartTime(DateUtils.getDateStrByFormat(taskMain.getStartTime(), "yyyy.MM.dd"));
        resp.setEndTime(DateUtils.getDateStrByFormat(taskMain.getEndTime(), "yyyy.MM.dd"));
        resp.setStorageCode(taskMain.getStorageCode());
        Set<String> status = new HashSet<String>();
        ModelTaskDetailVo detail;
        List<String> brands;
        for (ModelTaskAssignDetailsBean task : tasks) {
            detail = new ModelTaskDetailVo();
            detail.setCate(convertTaskCate(task));
            // 样机品类下品牌集合
            brands = Lists.transform(detail.getCate().getBrands(), new Function<ModelTaskBrandVo, String>(){
                @Override
                public String apply(ModelTaskBrandVo input) {
                    return input.getBrandCode();
                }
            });
            // 设置盘点数
            detail.setInventoryCnt(getInventoryNum(taskMain.getTaskId(), storeMan.getStoreCode(), task.getCateCode(), brands));
            // 根据门店,品类查询样机清单数量
            detail.setModelTotal(getModelMainListCnt(storeMan.getStoreCode(), task.getCateCode(), brands));
            // 设置任务状态
            if (TASK_OVER.equals(taskMain.getRunStatus())) {
                detail.setTaskStatusCode(ModelConstant.TASK_STATUS_CODE_JS);
            } else {
                // 根据品类品牌状态,区分出品类状态
                detail.setTaskStatusCode(getTaskStatusCode(task));
                // 如果是待盘点,则可进行盘点操作
                if (ModelConstant.TASK_STATUS_CODE_MP.equals(detail.getTaskStatusCode())) {
                    // 品牌盘点-03
                    status.add("03");
                }
            }
            // 设置分配人信息
            detail.setAssignPerson(this.queryStaffName(task.getAssignStaff()));
            details.add(detail);
        }
        // 任务未结束且如果有盘点任务,操作类型为盘点-03
        if (!TASK_OVER.equals(taskMain.getRunStatus()) && status.contains("03")) {
            resp.setOprType("03");
        }
        resp.setDetails(details);
        LOGGER.info("exit queryMyInventoryTaskDetail service,taskId={}", taskId);
        return resp;
    }
    
    /**
     * 封装品类品牌
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param task
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private ModelTaskCateVo convertTaskCate(ModelTaskAssignDetailsBean task) {
        List<ModelTaskBrandVo> branchs = new ArrayList<ModelTaskBrandVo>();
        ModelTaskCateVo cateVo = new ModelTaskCateVo();
        cateVo.setCateCode(task.getCateCode());
        cateVo.setCateName(task.getCateName());
        ModelTaskBrandVo brand = new ModelTaskBrandVo();
        brand.setBrandCode(task.getBranch9code());
        brand.setBrandName(task.getBranchName());
        branchs.add(brand);
        cateVo.setBrands(branchs);
        return cateVo;
    }
}
